package com.wsq.broadcastdemo

import android.content.Intent
import android.content.IntentFilter
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import broadcast.MyReceiver

class MainActivity : AppCompatActivity() {

    companion object{
        const val KEY = "broadcast"
        const val ACTION = "com.wsq.reciver"
    }

    lateinit var reciver: MyReceiver

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //1.向静态注册的广播接收器发送广播
//        sendStaticBroadcastDemo()


        //2.动态注册广播接收器，并发送广播
//        reciver = MyReceiver()
//        registerBroadcast()
//        sendBroadcastDemo()

        //3.动态注册本地广播接收器，并发送广播
        reciver = MyReceiver()
        registerLocalBroadcast()
        sendLocalBroadcastDemo()

    }

    override fun onDestroy() {
        super.onDestroy()

        unregisterBroadcast()
    }

    /**
     * 向静态注册的广播接收器发送广播
     *
     * api 26以后不能接收隐式广播
     */
    fun sendStaticBroadcastDemo(){
        val intent = Intent(MainActivity@this, MyReceiver::class.java)
        intent.putExtra(KEY, "静态注册")
        sendBroadcast(intent)
    }



    /**
     * 注册动态广播接收器
     */
    fun registerBroadcast(){
        var intentFilter = IntentFilter()
        intentFilter.addAction(ACTION)
        registerReceiver(reciver, intentFilter)
    }

    fun sendBroadcastDemo(){
        val intent = Intent(MainActivity@this, MyReceiver::class.java)
        intent.action = ACTION
        intent.putExtra(KEY, "动态注册")
        sendBroadcast(intent)
    }

    fun unregisterBroadcast(){
        unregisterReceiver(reciver)
    }

    /**
     * 动态注册本地广播接收器
     */
    fun registerLocalBroadcast(){
        var intentFilter = IntentFilter()
        intentFilter.addAction(ACTION)
        LocalBroadcastManager.getInstance(MainActivity@this).registerReceiver(reciver, intentFilter)
    }

    /**
     * 发送本地广播
     */
    fun sendLocalBroadcastDemo(){
        val intent = Intent(MainActivity@this, MyReceiver::class.java)
        intent.action = ACTION
        intent.putExtra(KEY, "本地广播")
//        sendBroadcast(intent)
        LocalBroadcastManager.getInstance(MainActivity@this).sendBroadcast(intent)
    }



}